var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require('fs')
// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

var app = express();

const configPath = path.join(__dirname, 'config');
const keyMapsPath = path.join(configPath, 'keyMaps')

// robot js
var robot = require("robotjs");
var keyPassTime = 16;
var keyGroup = ['alt', 'control', 'z']

function passGroupKey() {
  let KeyGroup = keyGroup
  for (const key in KeyGroup) {
    if (Object.hasOwnProperty.call(KeyGroup, key)) {
      const k = KeyGroup[key];
      robot.keyToggle(k, 'down')
    }
  }
  setTimeout(() => {
    for (const key in KeyGroup) {
      if (Object.hasOwnProperty.call(KeyGroup, key)) {
        const k = KeyGroup[key];
        robot.keyToggle(k, 'up')
      }

    }
  }, keyPassTime);
}
function toggleGroupKey(mode) {
  let KeyGroup = keyGroup
  for (const key in KeyGroup) {
    if (Object.hasOwnProperty.call(KeyGroup, key)) {
      const k = KeyGroup[key];
      robot.keyToggle(k, mode)
    }
  }
}
//配置post body解析
app.use(express.json())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 全局 中间件  解决所有路由的 跨域问题
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
  next()
})

app.get('/api/getKeyMaps', function (req, res) {
  try {
    var keyMaps = fs.readdirSync(keyMapsPath)
  } catch (error) {
    var keyMaps = []
  }
  res.send(JSON.stringify(keyMaps))
})
app.get('/api/getKeyMapData', function (req, res) {
  let name = req.query.name
  try {
    var keyMapData = JSON.parse(fs.readFileSync(path.join(keyMapsPath, name)).toString())
  } catch (error) {
    var keyMapData = null
  }
  res.send(JSON.stringify(keyMapData))
})
app.post('/api/setKeyMapData', function (req, res) {
  let name = req.body.name
  let data = req.body.data
  console.log(name)
  console.log(data)
  try {
    fs.writeFileSync(path.join(keyMapsPath, name), JSON.stringify(data))
  } catch (error) {
    res.send(JSON.stringify({ error }))
    return
  }
  res.send(JSON.stringify({ success: true }))
})
app.get('/api/keytoggle', function (req, res) {
  var response = {
    success: 'true'
  };
  console.log('keytoggle',req.query)

  keyGroup = req.query.key.split('+')
  toggleGroupKey(req.query.mode)
  res.send(JSON.stringify(response))
})
app.get('/api/keytap', function (req, res) {
  var response = {
    success: 'true'
  };
  keyGroup = req.query.key.split('+')
  passGroupKey()
  res.send(JSON.stringify(response))
})
app.post('/api/test', function (req, res) {
  console.log(req.body)
  var response = {
    first_name: 'bbbbb',
    last_name: '22222'
  };
  res.send(JSON.stringify(response))
})

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public/easy_deck_ui/dist/')));

// app.use('/', indexRouter);
// app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
app.listen(8192);
module.exports = app;
